package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.AddDeliveryInfoHistoryBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.GroupBookingBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.SecKillSubBean
import com.example.shushiyunsst.util.*
import com.example.wallet.db.UserInfoManager
import com.google.android.material.tabs.TabLayout
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString
import ikidou.reflect.TypeBuilder
import kotlinx.android.synthetic.main.ping_tuan_fragment.*
import java.lang.reflect.Type
import kotlin.math.abs

/**
 * 拼团
 * */
@Route(path = GROUP_BOOKING)
class GroupBookingFragment : SimpleListFragment<GroupBookingBean>(),
    TabLayout.OnTabSelectedListener, OnItemChildClickListener {

    companion object {
        fun newInstance(): GroupBookingFragment {
            val args = Bundle()

            val fragment = GroupBookingFragment()
            fragment.arguments = args
            return fragment
        }

        //拼团中
        const val Booking = "Booking"

        //参与中
        const val Attending = "1"

        //拼团记录
        const val BookedRecord = "2"

    }

    private var cml = AppGlobals.getApplication().getString(R.string.wallet_cml)

    private val tabMap = mapOf(
        "拼团中" to Booking,
        "参与中" to Attending,
        "拼团记录" to BookedRecord
    )

    private var currentType = Booking

    private lateinit var mTabLayout: TabLayout

    private val icon = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var haveDelivery = false

    private var lastInputPassWordTime = 0L

    private var time = 5 * 60 * 60 * 1000L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isAddDividerItemDecoration = false
    }

    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()

        addHeader(R.layout.ping_tuan_header_fragment)
        val mToolbar: Toolbar = mHeader.findViewById(R.id.mToolbar)
        mToolbar.title = "拼团"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mTabLayout = mHeader.findViewById(R.id.mTabLayout)
        for (e in tabMap) {
            mTabLayout.addTab(
                mTabLayout.newTab()
                    .setText(e.key)
                    .setTag(e.value)
            )
        }
        mTabLayout.addOnTabSelectedListener(this)

        mAdapter.addChildClickViewIds(R.id.chanJa, R.id.cancel, R.id.done,R.id.icon)

        mAdapter.setOnItemChildClickListener(this)

        checkDeliveryInfo()
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.icon->{
                val parentFragment = parentFragment
                if(parentFragment is BaseFragmentEx){
                    ARouter.getInstance()
                        .build(GOODS_DETAIL)
                        .withString(GOODS_ID, item.goodsId.toString())
                        .startNavigation(parentFragment)
                }else{
                    ARouter.getInstance()
                        .build(GOODS_DETAIL)
                        .withString(GOODS_ID, item.goodsId.toString())
                        .startNavigation(this)
                }
            }
            R.id.chanJa -> {
                if (haveDelivery) {
                    chanJaItemPop(item)
                } else {
                    Toast.makeText(_mActivity, "请添加收货地址", Toast.LENGTH_LONG).show()
                    ARouter.getInstance()
                        .build(ADD_DELIVERY_INFO)
                        .startNavigation(this)
                }

            }
            R.id.cancel -> {
                handCancel(item)
            }
            R.id.done -> {
                // GroupBookingBean.UN_REWARDING, GroupBookingBean.REWARDING
                if (item?.txStatus == GroupBookingBean.UN_REWARDING || item?.txStatus == GroupBookingBean.REWARDING) {
                    lookResult(item)
                }
            }
        }
    }

    private fun lookResult(item: GroupBookingBean) {
        val groupBookingLuckyPop = GroupBookingLuckyPop(_mActivity)
        groupBookingLuckyPop.setGbid("${item.gbid}")
        XPopup.Builder(_mActivity)
            .asCustom(groupBookingLuckyPop)
            .show()
    }

    //撤销
    private fun handCancel(item: GroupBookingBean?) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "gbid" to item?.gbid,
            "uid" to userInfo?.uid

        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.groupBuyCancel)
            .success {
                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                    onRefresh()
                }
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }

    private fun checkDeliveryInfo() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .url(R.string.queryMyAddrList)
            .raw(JSON.toJSONString(maps))
            .success {

                parseQueryMyAddressListDate(it)

            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }
            .build()
            .post()
    }

    private fun parseQueryMyAddressListDate(data: String?) {
        val obj = JSON.parseObject(data)
        val addressList = obj["addrList"]
        val array = JSON.parseArray(addressList.toString(), AddDeliveryInfoHistoryBean::class.java)
        haveDelivery = array.isNotEmpty()
    }

    private fun chanJaItemPop(item: GroupBookingBean?) {

        val currentTimeMillis = System.currentTimeMillis()
        if (abs(currentTimeMillis - lastInputPassWordTime) <= time) {

            chanJaItem(item)
            return
        }
        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)

                    hideSoftInput()
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            chanJaItem(item)
                            lastInputPassWordTime = System.currentTimeMillis()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    //参团
    private fun chanJaItem(item: GroupBookingBean?) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "gbid" to item?.gbid,
            "uid" to userInfo?.uid

        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.groupBuy)
            .success {
                Toast.makeText(_mActivity, "参与成功", Toast.LENGTH_LONG).show()
                if (!mSwipeRefreshLayout.isRefreshing) {
                    mSwipeRefreshLayout.isRefreshing = true
                    onRefresh()
                }
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }

    override fun getItemLayout(): Int {
        return R.layout.ping_tuan_fragment
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: GroupBookingBean?) {
        val luckyGroupPreFix = "幸运参团："
        val luckyGroupPreStr = "${item?.goodsName} + ${item?.givenCml} $cml"

        val heartenGroupPreFix = "参团鼓励："
        val heartenGroupPreStr = "返还 ${item?.gbPrice} $icon + ${item?.givenCmlFail} $icon 鼓励金"

        val chanJaStr = when (item?.txStatus) {
            GroupBookingBean.UN_ATTENDING -> "我要参加"
            GroupBookingBean.UN_REWARDING, GroupBookingBean.REWARDING -> "查看结果"
            GroupBookingBean.ATTENDING -> "撤销"
            GroupBookingBean.CANCEL -> "已撤销"
            else -> ""
        }

        helper?.setText(R.id.name, item?.goodsName)
            ?.setImageNetUrl(R.id.icon, item?.goodsLogo)
            ?.setText(R.id.count, "${item?.goodsNums}")
            ?.setText(R.id.chanJa, chanJaStr)
            ?.setText(R.id.cancel, chanJaStr)
            ?.setText(R.id.done, chanJaStr)
            ?.setText(R.id.singlePrice, "零售价：${item?.gbPriceOld} $icon")
            ?.setText(R.id.createTv, "发起时间：${item?.createTime}")
            ?.setText(R.id.bookedCount, "已参团：${item?.gbBuyNums}人")
            ?.setText(R.id.need, "成团条件：${item?.neededNums}人")
            ?.setText(
                R.id.price, JssSpannableString(_mActivity, "团购价 ${item?.gbPrice} $icon")
                    .first("${item?.gbPrice}")
                    .textColor(R.color.PrimaryColor)
                    .size(16)
                    .first(icon)
                    .textColor(R.color.PrimaryColor)
                    .size(10)
            )
            ?.setText(
                R.id.luckyGroup,
                JssSpannableString(_mActivity, "$luckyGroupPreFix$luckyGroupPreStr")
                    .first(luckyGroupPreFix)
                    .size(9)
                    .first(luckyGroupPreStr).size(9)
                    .textColor(R.color.PrimaryColor)
            )
            ?.setText(
                R.id.heartenGroup,
                JssSpannableString(_mActivity, "$heartenGroupPreFix$heartenGroupPreStr")
                    .first(heartenGroupPreFix)
                    .size(9)
                    .first(heartenGroupPreStr)
                    .textColor(R.color.PrimaryColor)
                    .size(9)
            )
            ?.setVisible(
                R.id.chanJa,
                item?.txStatus == GroupBookingBean.UN_ATTENDING

            )
            ?.setVisible(
                R.id.cancel,
                item?.txStatus == GroupBookingBean.ATTENDING
            )
            ?.setVisible(
                R.id.done,
                item?.txStatus == GroupBookingBean.UN_REWARDING
                        || item?.txStatus == GroupBookingBean.CANCEL
                        || item?.txStatus == GroupBookingBean.REWARDING
            )
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(GroupBookingBean::class.java)
            .endSubType()
            .build()
    }

    override fun netRequest() {


        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        when (currentType) {
            Booking -> {
                val map = mapOf(
                    "pageCount" to 10,
                    "pageIndex" to pageIndex,
                    "uid" to userInfo?.uid
                )
                RestClient.builder()
                    .raw(JSON.toJSONString(map))
                    .url(R.string.queryGroupBuyList)
                    .success {
                        parseDate(it)
                    }.error { _, _ -> onFailed() }
                    .failure { onFailed() }
                    .build().post()
            }
            BookedRecord, Attending -> {
                val map = mapOf(
                    "pageCount" to 10,
                    "pageIndex" to pageIndex,
                    "type" to currentType,
                    "uid" to userInfo?.uid
                )
                RestClient.builder()
                    .raw(JSON.toJSONString(map))
                    .url(R.string.queryMyGroupBuyingList)
                    .success {
                        parseDate(it)
                    }.error { _, _ -> onFailed() }
                    .failure { onFailed() }
                    .build().post()
            }
        }

    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        when (currentType) {
            Booking -> {
                val obj = JSON.parseObject(data)
                val groupBuyList = obj["groupBuyList"].toString()
                val array = JSON.parseArray(groupBuyList, GroupBookingBean::class.java)
                loadListDate(array)
            }
            BookedRecord, Attending -> {
                val obj = JSON.parseObject(data)
                val groupBuyList = obj["list"].toString()
                val array = JSON.parseArray(groupBuyList, GroupBookingBean::class.java)
                loadListDate(array)
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        mTabLayout.removeOnTabSelectedListener(this)
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        currentType = tab?.tag.toString()
        if (!mSwipeRefreshLayout.isRefreshing) {
            mSwipeRefreshLayout.isRefreshing = true
            onRefresh()
        }

    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }

    override fun onTabReselected(tab: TabLayout.Tab?) {

    }


}